const express= require('express');
const common = require('../../../libs/common');
const reg = require('../../../libs/reg');

let router = express.Router();
module.exports = router;

router.post('/',(req,res)=>{
    let {email,password} = req.body;
    if(!reg.mailReg.test(email)){
        let loginData={
            status:2,
            errMsg:"Please enter a valid email address"
        }
        res.send(loginData)
    }else if(!reg.pwdReg.test(password)){
        let loginData={
            status:2,
            errMsg:"Enter a combination of letters and numbers between 5 and 21"
        }
        res.send(loginData)
    }else{
        req.db.query(`SELECT ID,password FROM user WHERE username='${email}'`,(err,data)=>{
            if(err){
                res.sendStatus(500);
            }else if(data.length==0){
                let loginData={
                    status:2,
                    errMsg:"Wrong email or password"
                }
                res.send(loginData)
            }else{
                if(common.md5(password) == data[0].password){
                    let token = common.uuid();
                    req.session['shoe-user_ID']=data[0].ID;
                    req.session['shoe-email']=email;
                    req.session['shoe-token']=token;
                    let loginData={
                        status:1
                    }
                    req.client.set(data[0].ID,token);
                    res.send(loginData);
                }else{
                    let loginData={
                        status:2,
                        errMsg:"Wrong email or password"
                    }
                    res.send(loginData);
                }
            }
        })
    }
    
})
